package com.eapi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eapi.project.exception.BusinessException;
import com.eapi.project.model.entity.Invokerecord;
import com.eapi.project.service.InterfaceInfoService;
import com.eapi.project.service.InvokerecordService;
import com.eapi.project.service.UserInterfaceInfoService;
import com.eapi.project.service.UserService;
import com.eapi.eapicommom.model.entity.InterfaceInfo;
import com.eapi.eapicommom.model.entity.User;
import com.eapi.eapicommom.model.entity.UserInterfaceInfo;
import com.eapi.project.common.ErrorCode;
import com.eapi.project.mapper.UserInterfaceInfoMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
* @author lenovo
* @description 针对表【user_interface_info(用户调用接口关系)】的数据库操作Service实现
* @createDate 2024-03-14 18:49:35
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService {

    @Resource
    private UserService userService;

    @Resource
    InterfaceInfoService interfaceInfoService;

    @Resource
    InvokerecordService invokerecordService;

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
     Long id = userInterfaceInfo.getId();
     Long userId = userInterfaceInfo.getUserId();
     Long interfaceInfoId = userInterfaceInfo.getInterfaceInfoId();
     Integer totalNum = userInterfaceInfo.getTotalNum();
/*
     Integer leftNum = userInterfaceInfo.getLeftNum();
*/
     Integer status = userInterfaceInfo.getStatus();
     Date createTime = userInterfaceInfo.getCreateTime();
     Date updateTime = userInterfaceInfo.getUpdateTime();
     Integer isDelete = userInterfaceInfo.getIsDelete();


        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 创建时，所有参数必须非空
        if (add) {
            if (interfaceInfoId <= 0 || userId<= 0 ){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口或用户不存在");
            }
        }
/*        if (leftNum < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余次数不能小于0");
        }*/
    }

    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 查询调用接口所需积分
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(interfaceInfoId);
        Long invokeCosts = interfaceInfo.getPointsCost();

        // 获取用户的剩余积分
        User user = userService.getById(userId);
        Long remainingPoints = user.getRemainingPoints();

        // 判断用户剩余积分是否足够
        if(remainingPoints<=invokeCosts){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"积分不足");
        }

        // 更新invokeRecord表
        Invokerecord invokerecord = new Invokerecord();
        invokerecord.setInterfaceInfoId(interfaceInfoId);
        invokerecord.setUserId(userId);
        invokerecord.setInvokeCosts(invokeCosts);
        invokerecord.setInterfaceInfoName(interfaceInfo.getName());
        invokerecord.setDescription(interfaceInfo.getDescription());
        invokerecordService.insertInvoke(invokerecord);

        // 更新UserInterfaceInfo表中的数据
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        queryWrapper.eq("interfaceInfoId", interfaceInfoId);
        UserInterfaceInfo useInterfaceInfo = this.getOne(queryWrapper);
        if (useInterfaceInfo == null){
            UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
            userInterfaceInfo.setInterfaceInfoId(interfaceInfoId);
            userInterfaceInfo.setUserId(userId);
            this.save(userInterfaceInfo);
        }
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interfaceInfoId", interfaceInfoId);
        updateWrapper.eq("userId", userId);
        updateWrapper.setSql("totalNum = totalNum + 1");

        boolean update = this.update(updateWrapper);

        // 如果更新成功，修改用户剩余积分
        if(update){
            user.setRemainingPoints(remainingPoints-invokeCosts);
            userService.updateById(user);
        } else{
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"系统异常，请联系管理员");
        }


        return update;
    }
}




